package cn.wang.service;

import cn.wang.auth.pojo.UserInfo;
import cn.wang.auth.utils.JwtUtils;
import cn.wang.client.UserClient;
import cn.wang.common.Exceptions.impl.LyException;
import cn.wang.common.enums.impl.ExceptionEnum;
import cn.wang.cart.config.JwtProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import user.pojo.User;

@Service
public class LoginService {
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    UserClient userClient;


    public String login(String username, String password) {
        // 用户名或密码为空直接抛出异常
        if (StringUtils.isAnyBlank(username,password)) {
            throw new LyException(ExceptionEnum.USERNAME_OR_PASSWORD_IS_NULL);
        }
        // 通过user微服务对用户进行校验
        User user =null;
        try {
            user = userClient.queryUser(username, password);
        }catch (Exception e){
            throw  new LyException(ExceptionEnum.USERNAME_OR_PASSWORD_IS_NULL);
        }
        if (user == null) {
            throw new LyException(ExceptionEnum.USERNAME_OR_PASSWORD_IS_NULL);
        }
        // 生成jwt
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        return getToken(userInfo);
    }

    /**
     * 根据用户信息获取token
     * @param userInfo
     * @return
     */
    public String getToken(UserInfo userInfo) {
        try {
            String token = JwtUtils.generateToken(userInfo,
                    jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            return token;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.CREATE_TOKEN_ERROR);
        }
    }

    // 通过token来获取用户信息
    public UserInfo verify(String token) {
        try {
            UserInfo user = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.TOKEN_ERROR);
        }
    }
}
